//
//  SHKPeripheralManager.m
//  BabyBluetoothAppDemo
//
//  Created by 宋宏康 on 2020/5/17.
//  Copyright © 2020 刘彦玮. All rights reserved.
//

#import "SHKPeripheralManager.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyToy.h"
static NSString * const kHeartRateService = @"180D";
static NSString * const kHeartRateMeasurement = @"2A37";

static NSString * const kPAPAService = @"43421CBB-8873-4F6B-B9CF-E13864ADE2D0";
static NSString * const kPAPARWCharacter = @"3EB7D4A9-F1B4-41D3-AA5F-738B500E27B5";


@interface SHKPeripheralManager() <CBPeripheralManagerDelegate>
@property (nonatomic, strong) CBPeripheralManager *peripheralManager;
@property (nonatomic, strong) CBMutableCharacteristic *characteristic;
@property (nonatomic, strong) NSTimer *timer;


@property (nonatomic, strong) CBMutableCharacteristic *rwCharacteristic;
@property (nonatomic, strong) NSData *value;
@end

@implementation SHKPeripheralManager

- (instancetype)init
{
    self = [super init];
    if (self) {
       CBPeripheralManager *peripheralManager  =  [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
        self.peripheralManager = peripheralManager;
    }
    return self;
}

- (void)setupServices
{
    /// 创建服务
    CBUUID *serviceUuid = [CBUUID UUIDWithString:kHeartRateService];
    CBMutableService *services = [[CBMutableService alloc] initWithType:serviceUuid primary:YES];
    
    /// 创建特征值
    CBUUID *characteristicUuid = [CBUUID UUIDWithString:kHeartRateMeasurement];
    CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc] initWithType:characteristicUuid
                                                                                 properties:CBCharacteristicPropertyNotify value:nil permissions:(CBAttributePermissionsReadable | CBAttributePermissionsWriteable)];
    self.characteristic = characteristic;
    services.characteristics =  @[characteristic];
    
    /// 将服务加入到设备
    [self.peripheralManager addService:services];
}

- (void)setupReadWriteServices
{
    /// 创建服务
    CBUUID *serviceUuid = [CBUUID UUIDWithString:kPAPAService];
    CBMutableService *services = [[CBMutableService alloc] initWithType:serviceUuid primary:YES];
    
    /// 创建特征值
    CBUUID *characteristicUuid = [CBUUID UUIDWithString:kPAPARWCharacter];
    CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc] initWithType:characteristicUuid
                                                                                 properties:(CBCharacteristicPropertyRead | CBCharacteristicPropertyWrite)
                                                                                      value:nil
                                                                                permissions:(CBAttributePermissionsReadable | CBAttributePermissionsWriteable)];
    self.rwCharacteristic = characteristic;
    services.characteristics =  @[characteristic];
    
    /// 将服务加入到设备
    [self.peripheralManager addService:services];
}


- (void)startAd
{
    [self.peripheralManager startAdvertising:@{
        CBAdvertisementDataServiceUUIDsKey:@[
                [CBUUID UUIDWithString:kHeartRateService],
                [CBUUID UUIDWithString:kPAPAService]
        ]}];
}

- (void)stopAd
{
    [self.peripheralManager stopAdvertising];
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
    switch (peripheral.state) {
        case CBPeripheralManagerStateUnknown:
            NSLog(@">>>CBPeripheralManagerStateUnknown");
            break;
        case CBPeripheralManagerStateResetting:
            NSLog(@">>>CBPeripheralManagerStateResetting");
            break;
        case CBPeripheralManagerStateUnsupported:
            NSLog(@">>>CBPeripheralManagerStateUnsupported");
            break;
        case CBPeripheralManagerStateUnauthorized:
            NSLog(@">>>CBPeripheralManagerStateUnauthorized");
            break;
        case CBPeripheralManagerStatePoweredOff:
            NSLog(@">>>CBPeripheralManagerStatePoweredOff");
            break;
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@">>>CBPeripheralManagerStatePoweredOn");
            [self setupServices];
            [self setupReadWriteServices];
            break;
        default:
            break;
    }
}

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(nullable NSError *)error
{
    NSLog(@"%s  %@",__func__,error);
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic
{
    NSLog(@"%s",__func__);
    [self startTimer];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic
{
    NSLog(@"%s",__func__);
    [self stopTimer];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
{
    /// 读取数组请求通知
    NSLog(@"%s",__func__);
    if ([request.characteristic.UUID isEqual:self.rwCharacteristic.UUID]) {
        request.value = self.value;
        [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
    }
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests
{
    NSLog(@"%s",__func__);
    /// 写入数据
    CBATTRequest *request = requests.firstObject;
    if (request &&
        [request.characteristic.UUID isEqual:self.rwCharacteristic.UUID]) {
        self.value = request.value;
        NSLog(@"----:%d",[BabyToy ConvertDataToInt:request.value]);
        // 反馈成功
        [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
    }
}

- (void)measurementTimerFired:(NSTimer *)timer
{
    int value = arc4random() % 40 + 60;
    NSData *data = [NSData dataWithBytes:&value length:1];
    NSString *dataTip = [NSString stringWithFormat:@"值:%i, 数据:%@",value, data];
    BOOL success =  [self.peripheralManager updateValue:data forCharacteristic:self.characteristic onSubscribedCentrals:nil];
    NSLog(@"发送数据:%@  %@",dataTip, success? @"成功":@"失败");
}

- (void)startTimer
{
    [self stopTimer];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(measurementTimerFired:) userInfo:nil repeats:YES];
}

- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}
@end
